/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ticketManager.controller;

import java.util.jar.Attributes;
//import javax.faces.ManagedBean;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import ticketManager.ejb.HistoryDAO;
import ticketManager.ejb.UserDAO;
import ticketManager.model.ManagerUser;

/**
 *
 * @author shengruoya
 */
@ManagedBean(name = "login")
@RequestScoped
public class LoginControl_t {
    private String userName;
    private String password;
    @EJB
    UserDAO userBean_Tic;
    @EJB
    HistoryDAO hDAO;

    public LoginControl_t() {
    }
    
    public String doLogin(){
        FacesContext ctx = FacesContext.getCurrentInstance();
        ManagerUser U = userBean_Tic.dologin(userName, password);
        if (U != null) {
//            
            ctx.getExternalContext().getSessionMap().put("user", U);
            ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "login ok", "login ok"));         
            hDAO.loginEvent(U);
            return "logged";
        } else {
            ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "login incorrect", "login incorrect"));
            return "login";
        }
    }

    public String getLogin() {
        return userName;
    }

    public void setLogin(String login) {
        this.userName = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
    public String doLogout(){
        FacesContext ctx = FacesContext.getCurrentInstance();
        ManagerUser u = (ManagerUser)ctx.getExternalContext().getSessionMap().get("user");
        hDAO.logoutEvent(u);
        ctx.getExternalContext().getSessionMap().remove("user");
        ctx.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Logged out", "(disconnected)"));        
        return "index";
    }
}
